/**
 * 
 * 起迪科技 Copyright (c) 2014-2018 QiDi,Inc.All Rights Reserved.
 */
package cn.qidisoft.edu.hzjt.controller.scholarship;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.cxf.endpoint.Client;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.qidisoft.core.common.log.LoggerAdapter;
import cn.qidisoft.core.common.log.LoggerAdapterFactory;
import cn.qidisoft.core.common.pagination.Page;
import cn.qidisoft.core.common.pagination.PaginationBean;
import cn.qidisoft.core.util.DateUtil;
import cn.qidisoft.core.util.StringUtils;
import cn.qidisoft.core.util.json.JsonBinder;
import cn.qidisoft.core.util.moffice.excel.ExpExcelUtil;
import cn.qidisoft.core.util.moffice.excel.POIUtil;
import cn.qidisoft.core.util.uuid.UUIDGenerator;
import cn.qidisoft.core.web.customargument.bind.annotation.Token;
import cn.qidisoft.edu.hzjt.annotation.SysLogger;
import cn.qidisoft.edu.hzjt.constants.Constant;
import cn.qidisoft.edu.hzjt.controller.BaseController;
import cn.qidisoft.edu.hzjt.model.Grade;
import cn.qidisoft.edu.hzjt.model.ResponseResult;
import cn.qidisoft.edu.hzjt.model.ScholarshipApply;
import cn.qidisoft.edu.hzjt.model.Semester;
import cn.qidisoft.edu.hzjt.model.Student;
import cn.qidisoft.edu.hzjt.model.StudentClass;
import cn.qidisoft.edu.hzjt.model.StudentFamily;
import cn.qidisoft.edu.hzjt.model.UserEmployee;
import cn.qidisoft.edu.hzjt.model.ZxjStudentNationalGrant;
import cn.qidisoft.edu.hzjt.model.ZxjStudentPeopleGrant;
import cn.qidisoft.edu.hzjt.service.ICommonService;
import cn.qidisoft.edu.hzjt.service.IScholarshipApplyService;
import cn.qidisoft.edu.hzjt.service.IZxjStudentNationalGrantService;
import cn.qidisoft.edu.hzjt.service.IZxjStudentPeopleGrantService;
import cn.qidisoft.edu.hzjt.utils.AddSoapHeader;
import cn.qidisoft.edu.hzjt.utils.IdCardUtils;
import cn.qidisoft.edu.hzjt.utils.LogType;
import cn.qidisoft.edu.hzjt.utils.WsClientUrlConstants;
import cn.qidisoft.edu.hzjt.vo.FlowApprovalState;

/**
 * 
 * @author hxq
 * @version $Id: ScholarshipController.java, v 0.1 2018年11月5日 下午9:28:57 hxq Exp $
 */
@Controller
@RequestMapping("scholarship")
public class ScholarshipController {
  protected static final LoggerAdapter LOGGER =
      LoggerAdapterFactory.getLogger(LogType.HZJT_LOGGER.val);
  @Autowired
  private ICommonService commonService;
  @Autowired
  private IScholarshipApplyService scholarshipApplyService;
  @Autowired
  private IZxjStudentNationalGrantService zxjStudentNationalGrantService;
  @Autowired
  private IZxjStudentPeopleGrantService zxjStudentPeopleGrantervice;

  /**
   * 
   * 学生申请奖学金信息跳转页面
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/scholarshipStudentIndex")
  public String index(ModelMap model, HttpServletRequest request) {
    try {
      request.setAttribute("msg", BaseController.getParameter("msg"));
      BaseController.removeParameter("msg");
      List<Semester> yearList = BaseController.getYearList(commonService);
      // 获取当前学期
      BaseController.getSemester(model, commonService);
      if (!yearList.isEmpty()) {
        model.put("xnd", ((Semester) model.get("semester")).getXnd());
      }
      request.setAttribute("yearList", yearList);
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error(
          "学生申请奖学金跳转页面信息 scholarshipStudentIndex [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "scholarship/scholarshipStudent_list";
  }

  /**
   * 学生申请奖学金信息列表
   * 
   * @param model
   * @param request
   * @param pageSize
   * @param currentPage
   * @param data
   * @return
   */
  @RequestMapping(value = "/scholarshipStudentList")
  @ResponseBody
  public ResponseResult scholarshipStudentList(ModelMap model, HttpServletRequest request,
      @RequestParam(value = "rows", required = false) String pageSize,
      @RequestParam(value = "page", required = false) String currentPage, ScholarshipApply data) {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    ResponseResult result = new ResponseResult();
    try {
      if (loginType == 1) { // 学生
        Student student = (Student) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        data.setStuid(student.getXsid());
        Page page = BaseController.getPage(currentPage, pageSize, request, "xnd", "desc");
        data.setOrderField((String) request.getAttribute("orderField"));
        data.setOrderFlag((String) request.getAttribute("orderFlag"));
        PaginationBean<ScholarshipApply> paginationBean =
            scholarshipApplyService.queryScholarshipApplyPageList(data, page);
        if (paginationBean.getPageList().isEmpty()) {
          result.setRows(new ArrayList<ScholarshipApply>());
        } else {
          result.setRows(paginationBean.getPageList());
        }
        result.setTotal(paginationBean.getTotalRecords());
      } else {
        result.setRows(new ArrayList<ScholarshipApply>());
        result.setTotal(0);
      }
      return result;
    } catch (Exception e) {
      result.setRows(new ArrayList<ScholarshipApply>());
      result.setTotal(0);
      e.printStackTrace();
      LOGGER.error(
          "学生申请奖学金列表信息 scholarshipStudentList [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
    }
    return result;
  }

  /**
   * 学生奖学金申请跳转页面
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/addScholarshipStudentForward")
  @Token(save = true)
  public String addScholarshipStudentForward(ModelMap model, HttpServletRequest request) {
    try {
      Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
      if (loginType == 1) { // 学生
        Student student = (Student) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        // 获得学年信息
        List<Semester> yearList = BaseController.getYearList(commonService);
        // 获取当前学期
        BaseController.getSemester(model, commonService);
        if (!yearList.isEmpty()) {
          model.put("xnd", ((Semester) model.get("semester")).getXnd());
        }
        // 政治面貌
        BaseController.getCodeList(model, commonService, Constant.ZZMM_CODE);
        // 民族
        BaseController.getNationList(model, commonService, Constant.MZ_CODE);
        if (student.getCsrq() == null) {
          String birthday = IdCardUtils.getIdCardBirthday(student.getSfzh());
          student.setCsrq(DateUtil.parseStr2Date(birthday, "yyyy-MM-dd"));
        }
        // 获得学生的家庭成员信息
        StudentFamily family = new StudentFamily();
        family.setStuid(student.getXsid());
        List<StudentFamily> familyList = commonService.queryStudentByAllFamily(family);
        // 通过学年获得学期信息
        List<Semester> xqList =
            BaseController.getYearBySemesterList((Integer) model.get("xnd"), commonService);

        String cxGrade1 = null;
        String cxGrade2 = null;
        // 通过学期获得第一学期操行评定等级
        if (xqList != null && xqList.get(0) != null) {
          student.setYxid(((Semester) xqList.get(0)).getXqid());
          Student stu1 = commonService.queryByStudentConduct(student);
          if (stu1 != null) {
            cxGrade1 = stu1.getCxgrade();
          }
        }
        if (xqList != null && xqList.get(1) != null) {
          student.setYxid(((Semester) xqList.get(1)).getXqid());
          Student stu2 = commonService.queryByStudentConduct(student);
          if (stu2 != null) {
            cxGrade2 = stu2.getCxgrade();
          }
        }
        // 获得评定成绩信息
        student.setYxid(null);
        student.setXnd((Integer) model.get("xnd"));
        List<Student> studentScoreConductList =
            commonService.querySemesterStudentScoreConductList(student);
        model.put("cxGrade1", cxGrade1);
        model.put("cxGrade2", cxGrade2);
        model.put("yearList", yearList);
        model.put("student", student);
        model.put("familyList", familyList);
        model.put("studentScoreConductList", studentScoreConductList);
        model.put("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
      } else {
        BaseController.setParameter("msg", "没权限访问该页面");
        return "redirect:scholarshipStudentIndex";
      }
    } catch (Exception e) {
      LOGGER.error("学生申请奖学金信息 addScholarshipStudentForward [{}] error," + this.getClass().getName()
          + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "scholarship/addScholarshipStudent";
  }

  /**
   * 不同等级奖学金信息验证
   * 
   * @param request
   * @param response
   * @param xsid
   * @param xnd
   * @return
   */
  @RequestMapping(value = "/valdateStudentScholarship")
  public @ResponseBody String valdateStudentScholarship(HttpServletRequest request,
      HttpServletResponse response, @RequestParam(value = "xsid") Integer xsid,
      @RequestParam(value = "xnd") Integer xnd, @RequestParam(value = "jxjdj") Integer jxjdj) {
    response.setContentType("text/html;charset=utf-8");
    try {
      if (xsid == null || xnd == null || jxjdj == null) {
        return "1";
      } else {
        String flag = "-1";
        ScholarshipApply scholarshipApply = new ScholarshipApply();
        scholarshipApply.setStuid(xsid);
        scholarshipApply.setXnd(xnd);
        scholarshipApply.setJxjdj(jxjdj);
        // 判断评定等级情况
        int djNum = scholarshipApplyService.queryVerifyLevelScholarshipCout(scholarshipApply);
        if (djNum >= 1) { // 符合要求
          flag = "1";
        } else {
          // 判断评定成绩情况
          int scoreNum = scholarshipApplyService.queryVerifyScoreScholarshipCount(scholarshipApply);
          if (scoreNum >= 1) { // 不符合要求
            // 判断评定项目情况
            int pxxmNum = scholarshipApplyService.queryVerifyPXXMScholarshipCount(scholarshipApply);
            if (pxxmNum >= 1) { // 符合条件
              flag = "1";
            } else { // 不符合条件
              flag = "0";
            }
          } else { // 有两种情况，一种是没成绩，不符合条件，二是有成绩符合条件
            int isExistScoreNum =
                scholarshipApplyService.queryVerifyisExistScoreScholarshipCount(scholarshipApply);
            if (isExistScoreNum >= 1) { // 表示存在,符合条件
              flag = "1";
            } else { // 不符合条件
              // 判断评定项目情况
              int pxxmNum =
                  scholarshipApplyService.queryVerifyPXXMScholarshipCount(scholarshipApply);
              if (pxxmNum >= 1) { // 符合条件
                flag = "1";
              } else { // 不符合条件
                flag = "0";
              }
            }
          }
        }
        switch (jxjdj) {
          case 1:
            if (!"1".equals(flag)) {
              flag = "21"; // 你不符合一等奖学金申请条件，请你选择符合条件的选项
            }
            break;
          case 2:
            if (!"1".equals(flag)) {
              flag = "22"; // 你不符合二等奖学金申请条件，请你选择符合条件的选项
            }
            break;
          case 3:
            if (!"1".equals(flag)) {
              flag = "23"; // 你不符合三等奖学金申请条件，请你选择符合条件的选项
            }
            break;
          default:
            flag = "-1"; // 服务器异常
            break;
        }
        return flag;
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("获得符合项的推荐学生信息 getSemesterByStudentConductList [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      return "-1";
    }
  }

  /**
   * 学生奖学金信息验证
   * 
   * @param request
   * @param response
   * @param xsid
   * @param xnd
   * @return
   */
  @RequestMapping(value = "/valdateRepStudentScholarship")
  public @ResponseBody String valdateRepStudentScholarship(HttpServletRequest request,
      HttpServletResponse response, @RequestParam(value = "xsid") Integer xsid,
      @RequestParam(value = "xnd") Integer xnd) {
    response.setContentType("text/html;charset=utf-8");
    try {
      String sqid = request.getParameter("sqid");
      if (xsid == null || xnd == null) {
        return null;
      } else {
        ScholarshipApply scholarshipApply = new ScholarshipApply();
        scholarshipApply.setStuid(xsid);
        scholarshipApply.setXnd(xnd);
        if (!StringUtils.isNullValue(sqid)) {
          scholarshipApply.setSqid(Integer.parseInt(sqid));
        }
        // 判断评定等级情况
        int cout = scholarshipApplyService.queryRepByScholarshipCout(scholarshipApply);
        if (cout >= 1) {
          return "1";
        } else {
          return "0";
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("获得符合项的推荐学生信息 getSemesterByStudentConductList [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      return "-1";
    }
  }

  /**
   * 学生奖学金申请信息(学生端)保存功能
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/addStudentScholarship")
  @Token(remove = true, path = "scholarshipStudentIndex")
  @SysLogger(description = "学生新增奖学金信息", moduleName = "学生奖学金申请", method = "新增")
  public String addStudentScholarship(ModelMap model, HttpServletRequest request,
      ScholarshipApply scholarshipApply) {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    try {
      if (loginType == 1) { // 学生
        Student student = (Student) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        scholarshipApply.setGid(UUIDGenerator.genReqID());
        scholarshipApply.setStuid(student.getXsid());
        scholarshipApply.setCreatetime(new Date());
        scholarshipApply.setStates(FlowApprovalState.state0.getIndex()); // 未提交
        String jxjdj = request.getParameter("jxjdj");
        if (!StringUtils.isNullValue(jxjdj)) {
          scholarshipApply.setJxjdj(Integer.parseInt(jxjdj));
        }
        int sqid = scholarshipApplyService.addStudentScholarship(scholarshipApply);
        String flag = request.getParameter("flag");
        if (sqid >= 1 && !StringUtils.isNullValue(flag) && "1".equals(flag)) { // 新增跳转到修改页面
          // 根据guid获得zjid信息
          // ScholarshipApply gidScholarshipApply =
          // scholarshipApplyService.queryGidByScholarshipApply(scholarshipApply.getGid());
          BaseController.setParameter("msg", "保存成功");
          return "redirect:modiftyStudentScholarshipForward?sqid=" + sqid;
        } else if (sqid >= 1 && !StringUtils.isNullValue(flag) && "2".equals(flag)) { // 新增且继续新增
          BaseController.setParameter("msg", "保存成功");
          return "redirect:addScholarshipStudentForward";
        } else {
          BaseController.setParameter("msg", "保存失败");
          return "redirect:scholarshipStudentIndex";
        }
      } else {
        BaseController.setParameter("msg", "没权限访问该页面");
        return "redirect:scholarshipStudentIndex";
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error(
          "新增学生奖学金申请信息 addStudentScholarship [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
  }

  /**
   * 
   * 学生申请奖学金(学生端) 修改跳转页面
   * 
   * @param model
   * @param request
   * @param id
   * @return
   */
  @RequestMapping(value = "/modiftyStudentScholarshipForward", method = RequestMethod.GET)
  public String modiftyStudentScholarshipForward(ModelMap model, HttpServletRequest request,
      @RequestParam(value = "sqid") Integer id) {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    try {
      ScholarshipApply scholarshipApply = null;
      if (loginType == 1) { // 学生
        Student student = (Student) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        // 获取当前学期
        BaseController.getSemester(model, commonService);
        if (id != null) {
          scholarshipApply = scholarshipApplyService.queryByScholarshipApplyPk(id);
          if (scholarshipApply.getXnd() == null) {
            scholarshipApply.setXnd(((Semester) model.get("semester")).getXnd());
            model.put("xnd", ((Semester) model.get("semester")).getXnd());
          } else {
            model.put("xnd", scholarshipApply.getXnd());
          }
          model.put("scholarshipApply", scholarshipApply);
        }
        // 获得学年信息
        List<Semester> yearList = BaseController.getYearList(commonService);
        // 政治面貌
        BaseController.getCodeList(model, commonService, Constant.ZZMM_CODE);
        // 民族
        BaseController.getNationList(model, commonService, Constant.MZ_CODE);
        if (student.getCsrq() == null) {
          String birthday = IdCardUtils.getIdCardBirthday(student.getSfzh());
          student.setCsrq(DateUtil.parseStr2Date(birthday, "yyyy-MM-dd"));
        }
        // 获得学生的家庭成员信息
        StudentFamily family = new StudentFamily();
        family.setStuid(student.getXsid());
        List<StudentFamily> familyList = commonService.queryStudentByAllFamily(family);
        // 通过学年获得学期信息
        List<Semester> xqList =
            BaseController.getYearBySemesterList((Integer) model.get("xnd"), commonService);
        String cxGrade1 = null;
        String cxGrade2 = null;
        // 通过学期获得第一学期操行评定等级
        if (xqList != null && xqList.get(0) != null) {
          student.setYxid(((Semester) xqList.get(0)).getXqid());
          Student stu1 = commonService.queryByStudentConduct(student);
          if (stu1 != null) {
            cxGrade1 = stu1.getCxgrade();
          }
        }
        if (xqList != null && xqList.get(1) != null) {
          student.setYxid(((Semester) xqList.get(1)).getXqid());
          Student stu2 = commonService.queryByStudentConduct(student);
          if (stu2 != null) {
            cxGrade2 = stu2.getCxgrade();
          }
        }
        // 获得评定成绩信息
        student.setYxid(null);
        student.setXnd((Integer) model.get("xnd"));
        List<Student> studentScoreConductList =
            commonService.querySemesterStudentScoreConductList(student);
        model.put("cxGrade1", cxGrade1);
        model.put("cxGrade2", cxGrade2);
        model.put("yearList", yearList);
        model.put("student", student);
        model.put("familyList", familyList);
        model.put("studentScoreConductList", studentScoreConductList);
        List<ScholarshipApply> chekResultList = new ArrayList<ScholarshipApply>();
        if (scholarshipApply != null
            && scholarshipApply.getStates() != FlowApprovalState.state0.getIndex()) {
          // 审批流程记录信息
          Client client = AddSoapHeader.validateClient(WsClientUrlConstants.WS_FLOW_FACADE_REMOTE,
              student.getXh());
          if (client != null) {
            Object[] object =
                new Object[] {id + "", WsClientUrlConstants.XGGL_JXJ_AUDIT_CELL_ID, true};
            Object[] results = client.invoke("GetCustomAuditResults", object);
            if (results != null && results.length >= 1) {
              JSONObject jsonObject = (JSONObject) JSON.parse((String) results[0]);
              if (jsonObject.get("data") != null) {
                chekResultList =
                    JSON.parseArray(jsonObject.get("data").toString(), ScholarshipApply.class);
              }
            }
          }
        }
        model.put("chekResultList", chekResultList);
        model.put("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
        return "scholarship/editScholarshipStudent";
      } else {
        BaseController.setParameter("msg", "没权限访问该页面");
        return "redirect:scholarshipStudentIndex";
      }
    } catch (Exception e) {
      LOGGER.error("修改学生奖学金申请信息 modiftyStudentScholarshipForward [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }

  }

  /**
   * 
   * 学生期末总结(学生端) 修改
   * 
   * @param model
   * @param request
   * @param SemesterSummary
   * @return
   */
  @RequestMapping(value = "/modiftyStudentScholarship")
  @SysLogger(description = "学生修改奖学金申请信息", moduleName = "学生奖学金申请信息", method = "修改")
  public String modiftySemesterSummary(ModelMap model, HttpServletRequest request,
      ScholarshipApply scholarshipApply) {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    try {
      if (loginType == 1) { // 学生
        Student student = (Student) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        String jxjdj = request.getParameter("jxjdj");
        if (!StringUtils.isNullValue(jxjdj)) {
          scholarshipApply.setJxjdj(Integer.parseInt(jxjdj));
        }
        scholarshipApply.setCreatetime(new Date());
        scholarshipApply.setStates(FlowApprovalState.state0.getIndex());
        int num = scholarshipApplyService.modiftyStudentScholarship(scholarshipApply);
        if (num >= 1) {
          BaseController.setParameter("msg", "保存成功");
        } else {
          BaseController.setParameter("msg", "保存失败");
        }
      } else {
        BaseController.setParameter("msg", "没权限访问该页面");
        return "redirect:scholarshipStudentIndex";
      }
    } catch (Exception e) {
      LOGGER.error(
          "修改学生奖学金申请信息 modiftyStudentScholarship [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "redirect:modiftyStudentScholarshipForward?sqid=" + scholarshipApply.getSqid();

  }

  /**
   * 删除学生奖学金申请信息(学生端)
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/removeStudentScholarship", method = RequestMethod.POST)
  @SysLogger(description = "学生删除奖学金申请信息", moduleName = "学生奖学金申请信息", method = "删除")
  public String removeStudentScholarship(ModelMap model, HttpServletRequest request) {
    try {
      String[] idList = request.getParameter("idList").split(",");
      if (idList.length >= 1) {
        int num = scholarshipApplyService.removeStudentScholarship(idList);
        if (num >= 1) {
          BaseController.setParameter("msg", "删除成功");
        } else {
          BaseController.setParameter("msg", "删除失败");
        }
      }
      return "redirect:scholarshipStudentIndex";
    } catch (Exception e) {
      LOGGER.error(
          "删除学生奖学金申请信息 removeStudentScholarship [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
  }

  /**
   * 学生奖学金申请提交(学生端)
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/submitStudentScholarship")
  @SysLogger(description = "学生提交奖学金申请信息", moduleName = "学生奖学金申请信息", method = "提交")
  public String submitStudentScholarship(ModelMap model, HttpServletRequest request,
      @RequestParam(value = "sqid") Integer sqid) {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    try {
      if (loginType == 1) { // 学生
        Student student = (Student) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        if (sqid >= 1) {
          Client client = AddSoapHeader.validateClient(WsClientUrlConstants.WS_FLOW_FACADE_REMOTE,
              student.getXh());
          if (client != null) {
            ScholarshipApply scholarshipApply =
                scholarshipApplyService.queryByScholarshipApplyPk(sqid);
            HashMap<String, Object> conditionDataMap = new HashMap<String, Object>();
            // conditionDataMap.put("sqid", scholarshipApply.getSqid());
            conditionDataMap.put("xnd", scholarshipApply.getXnd());
            conditionDataMap.put("stuid", scholarshipApply.getStuid());
            conditionDataMap.put("xm", student.getXm());
            conditionDataMap.put("xh", student.getXh());
            conditionDataMap.put("bjid", scholarshipApply.getBjid());
            conditionDataMap.put("bjmc", student.getBjmc());
            conditionDataMap.put("zzmm", scholarshipApply.getZzmm());
            conditionDataMap.put("mz", scholarshipApply.getMz());
            conditionDataMap.put("jxjdj", scholarshipApply.getJxjdj());
            // conditionDataMap.put("states", FlowApprovalState.state2.getIndex());
            conditionDataMap.put("njid", student.getNjid());
            conditionDataMap.put("njmc", student.getNjmc());
            conditionDataMap.put("zyid", student.getZyid());
            conditionDataMap.put("zymc", student.getZymc());
            Object[] object = new Object[] {WsClientUrlConstants.XGGL_JXJ_AUDIT_CELL_ID,
                scholarshipApply.getSqid() + "", true, null, JsonBinder.toJson(conditionDataMap)};
            // 处理提交
            ScholarshipApply scholarshipApply2 = new ScholarshipApply();
            scholarshipApply2.setSqid(sqid);
            scholarshipApply2.setCreatetime(scholarshipApply.getCreatetime());
            scholarshipApply2.setStates(scholarshipApply.getStates());
            scholarshipApply.setStates(FlowApprovalState.state2.getIndex());
            int num = scholarshipApplyService.submitStudentScholarship(scholarshipApply);
            if (num >= 1) { // 提交成功
              Object[] results = client.invoke("SubmitFlow", object);
              if (results == null || results.length == 0) {
                // scholarshipApply2.setCreatetime(scholarshipApply.getCreatetime());
                // scholarshipApply2.setStates(scholarshipApply.getStates());
                scholarshipApplyService.submitStudentScholarship(scholarshipApply2);
                BaseController.setParameter("msg", "调用流程中发生了服务器异常，提交奖学金申请信息失败");
              } else {
                JSONObject jsonObject = (JSONObject) JSON.parse((String) results[0]);
                if (!"success".equals(jsonObject.get("status"))) {
                  // scholarshipApply2
                  // .setCreatetime(scholarshipApply.getCreatetime());
                  // scholarshipApply2.setStates(scholarshipApply.getStates());
                  scholarshipApplyService.submitStudentScholarship(scholarshipApply2);
                  BaseController.setParameter("msg", jsonObject.get("errMsg"));
                } else {
                  BaseController.setParameter("msg", "提交成功");
                }
              }
            } else {
              BaseController.setParameter("msg", "提交失败");
            }
          }
          return "redirect:modiftyStudentScholarshipForward?sqid=" + sqid;
        }
      } else {
        BaseController.setParameter("msg", "您没权限访问该页面");
        return "redirect:scholarshipStudentIndex";
      }
    } catch (Exception e) {
      LOGGER.error(
          "提交学生奖学金申请信息 submitStudentScholarship [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return null;
  }

  /**
   * 
   * 学生申请奖学金审核信息跳转页面
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/scholarshipStudentCheckIndex")
  public String scholarshipStudentCheckIndex(ModelMap model, HttpServletRequest request) {
    try {
      request.setAttribute("msg", BaseController.getParameter("msg"));
      BaseController.removeParameter("msg");
      // 获得年级信息
      BaseController.getGradeList(model, commonService);
      // 专业信息
      BaseController.getSpecialityList(model, commonService);
      // 班级信息
      model.put("classList", new ArrayList<StudentClass>());
      List<Semester> yearList = BaseController.getYearList(commonService);
      // 获取当前学期
      BaseController.getSemester(model, commonService);
      if (!yearList.isEmpty()) {
        model.put("xnd", ((Semester) model.get("semester")).getXnd());
      }
      request.setAttribute("yearList", yearList);
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("学生申请奖学金审核信息跳转页面信息 scholarshipStudentCheckIndex [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "scholarship/scholarshipStudent_auditList";
  }

  /**
   * 学生申请奖学金信息审核列表
   * 
   * @param model
   * @param request
   * @param pageSize
   * @param currentPage
   * @param data
   * @return
   */
  @RequestMapping(value = "/scholarshipStudentAuditList")
  @ResponseBody
  public ResponseResult scholarshipStudentAuditList(ModelMap model, HttpServletRequest request,
      @RequestParam(value = "rows", required = false) String pageSize,
      @RequestParam(value = "page", required = false) String currentPage, ScholarshipApply data) {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    ResponseResult result = new ResponseResult();
    try {
      BaseController.removeParameter("msg");
      List<ScholarshipApply> pageList = new ArrayList<ScholarshipApply>();
      int totalRecords = 0;
      if (loginType == 2) { // 老师
        UserEmployee userEmployee =
            (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        // Page page = BaseController.getPage(currentPage, pageSize, request, "xnd", "desc");
        // data.setOrderField((String) request.getAttribute("orderField"));
        // data.setOrderFlag((String) request.getAttribute("orderFlag"));
        // data.setStates(FlowApprovalState.state0.getIndex()); // 未提交状态
        if (StringUtils.isNullValue(data.getDdlStepState())) {
          data.setDdlStepState("2");
        } else if ("-1".equals(data.getDdlStepState())) {
          data.setDdlStepState(null);
        }
        if (StringUtils.isNullValue(data.getDdlUserState())) {
          data.setDdlUserState("0");
        } else if ("-1".equals(data.getDdlUserState())) {
          data.setDdlUserState(null);
        }
        // if (!StringUtils.isNullValue(data.getDdlStates()) && "-1".equals(data.getDdlStates())) {
        // data.setDdlStates(null);
        // }

        String params = validateQueryParams(data);
        Client client = AddSoapHeader.validateClient(WsClientUrlConstants.WS_FLOW_FACADE_REMOTE,
            userEmployee.getUserid());
        if (client != null) {
          Page page =
              BaseController.getPage(currentPage, pageSize, request, "reSubmitTime", "desc");
          Object[] object =
              new Object[] {WsClientUrlConstants.XGGL_JXJ_AUDIT_CELL_ID, page.getCurrPage(),
                  page.getPageSize(), params, (String) request.getAttribute("orderField") + " "
                      + (String) request.getAttribute("orderFlag")};
          Object[] results = client.invoke("GetUserAuditFlowData_LowerOrder", object);
          if (results == null || results.length == 0) {
            // BaseController.setParameter("msg", "调用流程中发生了服务器异常，提交奖学金申请信息失败");
            result.setMsg("调用流程中发生了服务器异常，提交奖学金申请信息失败");
          } else {
            JSONObject jsonObject = (JSONObject) JSON.parse((String) results[0]);
            if (!"success".equals(jsonObject.get("status"))) {
              result.setMsg(jsonObject.get("errMsg"));
            } else {
              if (jsonObject.get("rowCount") != null) {
                totalRecords = (int) jsonObject.get("rowCount");
              }
              if (jsonObject.get("data") != null) {
                pageList =
                    JSON.parseArray(String.valueOf(jsonObject.get("data")), ScholarshipApply.class);
                totalRecords = pageList.size();
              }
            }
          }
          // PaginationBean<ScholarshipApply> paginationBean =
          // scholarshipApplyService.queryScholarshipApplyAuditPageList(data, page);
          result.setTotal(totalRecords);
          result.setRows(pageList);
          return result;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      result.setTotal(0);
      result.setRows(new ArrayList<ScholarshipApply>());
      LOGGER.error("学生申请奖学金信息审核列表 scholarshipStudentAuditList [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
    }
    return result;
  }

  /**
   * 获得查询条件
   * 
   * @param data
   * @return
   */
  private static String validateQueryParams(ScholarshipApply data) {
    HashMap<String, Object> conditionDataMapList = new HashMap<String, Object>();
    StringBuilder sb = new StringBuilder(200);
    String paramStr = "";
    sb.append("[");
    if (!StringUtils.isNullValue(data.getDdlStates())) {
      conditionDataMapList.clear();
      conditionDataMapList.put("FieldName", "Sys_ApprovalInfo.flowState");
      conditionDataMapList.put("Value", data.getDdlStates());
      // conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
      sb.append(JsonBinder.toJson(conditionDataMapList) + ",");
    }
    if (!StringUtils.isNullValue(data.getDdlStepState())) {
      conditionDataMapList.clear();
      conditionDataMapList.put("FieldName", "Sys_ApprovalInfoStep.stepState");
      conditionDataMapList.put("Value", data.getDdlStepState());
      // conditionDataMapList.put("NeedQuotes", false); // 是否需要单引号
      sb.append(JsonBinder.toJson(conditionDataMapList) + ",");
    }
    if (!StringUtils.isNullValue(data.getDdlUserState())) {
      conditionDataMapList.clear();
      conditionDataMapList.put("FieldName", "Sys_ApprovalInfoResult.userState");
      conditionDataMapList.put("Value", data.getDdlUserState());
      // conditionDataMapList.put("NeedQuotes", false); // 是否需要单引号
      sb.append(JsonBinder.toJson(conditionDataMapList) + ",");
    }
    if (data.getXnd() != null) {
      conditionDataMapList.clear();
      conditionDataMapList.put("FieldName", "xnd");
      conditionDataMapList.put("Value", data.getXnd());
      conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
      sb.append(JsonBinder.toJson(conditionDataMapList) + ",");
    }
    if (!StringUtils.isNullValue(data.getXh())) {
      conditionDataMapList.clear();
      conditionDataMapList.put("FieldName", "xh");
      conditionDataMapList.put("Value", data.getXh());
      conditionDataMapList.put("Operator", "Like");
      sb.append(JsonBinder.toJson(conditionDataMapList) + ",");
    }
    if (!StringUtils.isNullValue(data.getXm())) {
      conditionDataMapList.clear();
      conditionDataMapList.put("FieldName", "xm");
      conditionDataMapList.put("Value", data.getXh());
      conditionDataMapList.put("Operator", "Like");
      sb.append(JsonBinder.toJson(conditionDataMapList) + ",");
    }
    if (data.getNjid() != null) {
      conditionDataMapList.clear();
      conditionDataMapList.put("FieldName", "njid");
      conditionDataMapList.put("Value", data.getNjid());
      conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
      sb.append(JsonBinder.toJson(conditionDataMapList) + ",");
    }
    if (data.getZyid() != null) {
      conditionDataMapList.clear();
      conditionDataMapList.put("FieldName", "zyid");
      conditionDataMapList.put("Value", data.getZyid());
      conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
      sb.append(JsonBinder.toJson(conditionDataMapList) + ",");
    }
    if (data.getBjid() != null) {
      conditionDataMapList.clear();
      conditionDataMapList.put("FieldName", "bjid");
      conditionDataMapList.put("Value", data.getBjid());
      conditionDataMapList.put("NeedQuotes", true); // 是否需要单引号
      sb.append(JsonBinder.toJson(conditionDataMapList) + ",");
    }
    if (sb.toString().length() >= 2) {
      paramStr = sb.substring(0, sb.length() - 1);
    } else {
      paramStr = sb.toString();
    }
    paramStr = paramStr + "]";
    return paramStr;
  }

  /**
   * 
   * 学生申请奖学金(审核端) 跳转页面
   * 
   * @param model
   * @param request
   * @param id
   * @return
   */
  @RequestMapping(value = "/auditStudentScholarshipForward", method = RequestMethod.GET)
  public String auditStudentScholarshipForward(ModelMap model, HttpServletRequest request,
      @RequestParam(value = "sqid") Integer id) {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    try {
      if (loginType == 2) { // 老师
        UserEmployee userEmployee =
            (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        String cxGrade1 = null;
        String cxGrade2 = null;
        List<StudentFamily> familyList = new ArrayList<StudentFamily>();
        List<Student> studentScoreConductList = new ArrayList<Student>();
        ScholarshipApply scholarshipApply = new ScholarshipApply();
        if (id != null) {
          ScholarshipApply scholarshipApplyAudit = new ScholarshipApply();
          scholarshipApplyAudit.setSqid(id);
          scholarshipApply =
              scholarshipApplyService.queryScholarshipApplyAuditPK(scholarshipApplyAudit);
          model.put("scholarshipApply", scholarshipApply);
          if (scholarshipApplyAudit.getCsrq() == null) {
            String birthday = IdCardUtils.getIdCardBirthday(scholarshipApply.getSfzh());
            scholarshipApplyAudit.setCsrq(DateUtil.parseStr2Date(birthday, "yyyy-MM-dd"));
          }
          // 获得学生的家庭成员信息
          StudentFamily family = new StudentFamily();
          family.setStuid(scholarshipApply.getStuid());
          familyList = commonService.queryStudentByAllFamily(family);
          // 通过学年获得学期信息
          List<Semester> xqList =
              BaseController.getYearBySemesterList(scholarshipApply.getXnd(), commonService);

          Student student = new Student();
          student.setXsid(scholarshipApply.getStuid());
          // 通过学期获得第一学期操行评定等级
          if (xqList != null && xqList.get(0) != null) {
            student.setYxid(((Semester) xqList.get(0)).getXqid());
            Student stu1 = commonService.queryByStudentConduct(student);
            if (stu1 != null) {
              cxGrade1 = stu1.getCxgrade();
            }
          }
          if (xqList != null && xqList.get(1) != null) {
            student.setYxid(((Semester) xqList.get(1)).getXqid());
            Student stu2 = commonService.queryByStudentConduct(student);
            if (stu2 != null) {
              cxGrade2 = stu2.getCxgrade();
            }
          }
          // 获得评定成绩信息
          student.setYxid(null);
          student.setXnd(scholarshipApply.getXnd());
          studentScoreConductList = commonService.querySemesterStudentScoreConductList(student);

        }
        // 获取审评结果
        model.put("cxGrade1", cxGrade1);
        model.put("cxGrade2", cxGrade2);
        model.put("familyList", familyList);
        model.put("studentScoreConductList", studentScoreConductList);
        model.put("scholarshipApply", scholarshipApply);
        // 获得审批记录信息
        List<ScholarshipApply> chekResultList = new ArrayList<ScholarshipApply>();
        String appId = request.getParameter("appId");
        String reId = request.getParameter("reId");
        Integer checkFlag = 0; // 是否可以审核
        if (!StringUtils.isNullValue(appId)) {
          Client client = AddSoapHeader.validateClient(WsClientUrlConstants.WS_FLOW_FACADE_REMOTE,
              userEmployee.getUserid());
          if (client != null) {
            Object[] object = new Object[] {Integer.parseInt(appId), true};
            Object[] results = client.invoke("GetAdminAuditResults", object);
            if (results != null && results.length >= 1) {
              JSONObject jsonObject = (JSONObject) JSON.parse((String) results[0]);
              if (jsonObject.get("data") != null) {
                chekResultList =
                    JSON.parseArray(jsonObject.get("data").toString(), ScholarshipApply.class);
              }
            }
            // 获得当前用户是否审批过,根据状态
            if (!StringUtils.isNullValue(reId)) {
              Object[] object2 = new Object[] {reId};
              Object[] results2 = client.invoke("GetFlowAuditInfo", object2);
              if (results2 != null && results2.length >= 1) {
                JSONObject jsonObject2 = (JSONObject) JSON.parse((String) results2[0]);
                if (jsonObject2.get("userIsAuditing") != null) {
                  if ((boolean) jsonObject2.get("userIsAuditing") == true) {
                    checkFlag = 1; // 可以审核
                  } else {
                    checkFlag = 0; // 可以审核
                  }
                }
              }
            }
          }
        }
        model.put("chekResultList", chekResultList);
        model.put("reId", reId);
        model.put("checkFlag", checkFlag);
        model.put("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
        return "scholarship/auditScholarshipStudent";
      } else {
        BaseController.setParameter("msg", "没权限访问该页面");
        return "redirect:scholarshipStudentCheckIndex";
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("学生申请奖学金(审核端) auditStudentScholarshipForward [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }

  }

  /**
   * 学生奖学金申请审核(审核生端)
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/auditStudentScholarship")
  @SysLogger(description = "老师审核学生奖学金申请信息", moduleName = "学生奖学金审核信息", method = "审核")
  public String auditStudentScholarship(ModelMap model, HttpServletRequest request,
      @RequestParam(value = "sqid") Integer sqid, @RequestParam(value = "states") Integer states,
      @RequestParam(value = "reId") Integer reId) {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    try {
      if (loginType == 2) { // 老师
        UserEmployee userEmployee =
            (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        if (sqid >= 1) {
          // 审批流程
          Client client = AddSoapHeader.validateClient(WsClientUrlConstants.WS_FLOW_FACADE_REMOTE,
              userEmployee.getUserid());
          ScholarshipApply scholarshipApply = new ScholarshipApply();
          scholarshipApply.setSqid(sqid);
          boolean bool = false; // 流程是否结束
          if (client != null) {
            String spyj = request.getParameter("spyj");
            Object[] object = new Object[] {reId, states == 3 ? true : false, spyj, null};
            Object[] results = client.invoke("DoAudit", object);
            if (results != null && results.length >= 1) {
              JSONObject jsonObject = (JSONObject) JSON.parse((String) results[0]);
              if (jsonObject.get("success") != null
                  && true == (boolean) jsonObject.get("success")) { // 流程审核通过
                if (jsonObject.get("flowFinished") != null
                    && true == (boolean) jsonObject.get("flowFinished")
                    && jsonObject.get("flowState") != null
                    && ((Integer) jsonObject.get("flowState"))
                        .intValue() == (FlowApprovalState.state3.getIndex()).intValue()) { // 标识流程结束，将数据库状态修改成审核通过
                  scholarshipApply.setStates(FlowApprovalState.state3.getIndex());
                  bool = true;
                } else if (jsonObject.get("flowFinished") != null
                    && false == (boolean) jsonObject.get("flowFinished")
                    && jsonObject.get("flowState") != null
                    && ((Integer) jsonObject.get("flowState"))
                        .intValue() == (FlowApprovalState.state1.getIndex()).intValue()) {
                  scholarshipApply.setStates(FlowApprovalState.state1.getIndex());
                  bool = true;
                } else if (jsonObject.get("flowFinished") != null
                    && false == (boolean) jsonObject.get("flowFinished")
                    && jsonObject.get("flowState") != null
                    && ((Integer) jsonObject.get("flowState"))
                        .intValue() == (FlowApprovalState.state2.getIndex()).intValue()) {
                  scholarshipApply.setStates(FlowApprovalState.state2.getIndex());
                  bool = true;
                } else if (jsonObject.get("flowFinished") != null
                    && false == (boolean) jsonObject.get("flowFinished")
                    && jsonObject.get("flowState") != null
                    && ((Integer) jsonObject.get("flowState"))
                        .intValue() == (FlowApprovalState.state8.getIndex()).intValue()) {
                  scholarshipApply.setStates(FlowApprovalState.state8.getIndex());
                  bool = true;
                } else {
                  bool = false; // 标识流程审核未结束
                }
                if (bool == true) { // 代表流程结束后才能将数据状态更新
                  int num = scholarshipApplyService.auditStudentScholarship(scholarshipApply);
                  if (num >= 1) {
                    BaseController.setParameter("msg", "审核成功");
                  } else {
                    BaseController.setParameter("msg", "审核失败");
                  }
                }
              } else {
                BaseController.setParameter("msg", "审核失败");
              }

            } else {
              BaseController.setParameter("msg", "流程服务器异常，未返回结果信息，审核失败");
            }
          }
        } else {
          BaseController.setParameter("msg", "审核的数据不存在");
        }
      } else {
        BaseController.setParameter("msg", "没权限访问该页面");
      }
      return "redirect:scholarshipStudentCheckIndex";
    } catch (Exception e) {
      LOGGER.error(
          "学生审核奖学金申请信息 auditStudentScholarship [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
  }

  /**
   * 
   * 学生申请奖学金信息（管理端）
   * 
   * @param model
   * @param request
   * @return
   */
  @RequestMapping(value = "/scholarshipStudentManagerIndex")
  public String scholarshipStudentManagerIndex(ModelMap model, HttpServletRequest request) {
    try {
      Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
      request.setAttribute("msg", BaseController.getParameter("msg"));
      BaseController.removeParameter("msg");
      if (loginType == 2) { // 老师端
        BaseController.getClassListAndBzrid(request, model, commonService, loginType);
        if (model.get(BaseController.STUDENT_BZRID) != null
            && (((Integer) model.get(BaseController.STUDENT_BZRID)).equals(Constant.IS_BZR))) {
          model.put(BaseController.STUDENT_BZRID,
              (Integer) model.get(BaseController.STUDENT_BZRID));
        }
        // 获得年级信息
        BaseController.getGradeList(model, commonService);
        // 专业信息
        BaseController.getSpecialityList(model, commonService);
        // 班级信息
        model.put("classList", new ArrayList<StudentClass>());
        List<Semester> yearList = BaseController.getYearList(commonService);
        // 获取当前学期
        BaseController.getSemester(model, commonService);
        if (!yearList.isEmpty()) {
          model.put("xnd", ((Semester) model.get("semester")).getXnd());
        }
        request.setAttribute("yearList", yearList);
      }

    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("学生申请奖学金审核信息跳转页面信息 scholarshipStudentCheckIndex [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "scholarship/scholarshipStudent_managerList";
  }

  /**
   * 学生申请奖学金信息列表（管理端）
   * 
   * @param model
   * @param request
   * @param pageSize
   * @param currentPage
   * @param data
   * @return
   */
  @RequestMapping(value = "/scholarshipStudentManagerList")
  @ResponseBody
  public ResponseResult scholarshipStudentManagerList(ModelMap model, HttpServletRequest request,
      @RequestParam(value = "rows", required = false) String pageSize,
      @RequestParam(value = "page", required = false) String currentPage, ScholarshipApply data) {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    ResponseResult result = new ResponseResult();
    try {
      if (loginType == 2) { // 老师
        UserEmployee userEmployee =
            (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        Page page = BaseController.getPage(currentPage, pageSize, request, "xnd", "desc");
        String bzr = request.getParameter("bzr");
        data.setOrderField((String) request.getAttribute("orderField"));
        data.setOrderFlag((String) request.getAttribute("orderFlag"));
        data.setStates(FlowApprovalState.state3.getIndex());
        if (Constant.IS_BZR.equals(bzr)) {
          data.setBzrid(userEmployee.getEmid());
        }
        PaginationBean<ScholarshipApply> paginationBean =
            scholarshipApplyService.queryScholarshipApplyManagerPageList(data, page);
        if (paginationBean.getPageList().isEmpty()) {
          result.setRows(new ArrayList<ScholarshipApply>());
        } else {
          result.setRows(paginationBean.getPageList());
        }
        result.setTotal(paginationBean.getTotalRecords());
      } else {
        result.setTotal(0);
        result.setRows(new ArrayList<ScholarshipApply>());
      }
      return result;
    } catch (Exception e) {
      e.printStackTrace();
      result.setTotal(0);
      result.setRows(new ArrayList<ScholarshipApply>());
      LOGGER.error("学生申请奖学金信息列表（管理端） scholarshipStudentManagerList [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
    }
    return result;
  }

  /**
   * 
   * 学生申请奖学金(审核端) 跳转页面
   * 
   * @param model
   * @param request
   * @param id
   * @return
   */
  @RequestMapping(value = "/viewStudentScholarshipManagerForward", method = RequestMethod.GET)
  public String viewStudentScholarshipManagerForward(ModelMap model, HttpServletRequest request,
      @RequestParam(value = "sqid") Integer id) {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    try {
      if (loginType == 2) { // 老师
        UserEmployee userEmployee =
            (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        String cxGrade1 = null;
        String cxGrade2 = null;
        List<StudentFamily> familyList = new ArrayList<StudentFamily>();
        List<Student> studentScoreConductList = new ArrayList<Student>();
        ScholarshipApply scholarshipApply = new ScholarshipApply();
        if (id != null) {
          ScholarshipApply scholarshipApplyAudit = new ScholarshipApply();
          scholarshipApplyAudit.setSqid(id);
          scholarshipApply =
              scholarshipApplyService.queryScholarshipApplyAuditPK(scholarshipApplyAudit);
          model.put("scholarshipApply", scholarshipApply);
          if (scholarshipApplyAudit.getCsrq() == null) {
            String birthday = IdCardUtils.getIdCardBirthday(scholarshipApply.getSfzh());
            scholarshipApplyAudit.setCsrq(DateUtil.parseStr2Date(birthday, "yyyy-MM-dd"));
          }
          // 获得学生的家庭成员信息
          StudentFamily family = new StudentFamily();
          family.setStuid(scholarshipApply.getStuid());
          familyList = commonService.queryStudentByAllFamily(family);
          // 通过学年获得学期信息
          List<Semester> xqList =
              BaseController.getYearBySemesterList(scholarshipApply.getXnd(), commonService);

          Student student = new Student();
          student.setXsid(scholarshipApply.getStuid());
          // 通过学期获得第一学期操行评定等级
          if (xqList != null && xqList.get(0) != null) {
            student.setYxid(((Semester) xqList.get(0)).getXqid());
            Student stu1 = commonService.queryByStudentConduct(student);
            if (stu1 != null) {
              cxGrade1 = stu1.getCxgrade();
            }
          }
          if (xqList != null && xqList.get(1) != null) {
            student.setYxid(((Semester) xqList.get(1)).getXqid());
            Student stu2 = commonService.queryByStudentConduct(student);
            if (stu2 != null) {
              cxGrade2 = stu2.getCxgrade();
            }
          }
          // 获得评定成绩信息
          student.setYxid(null);
          student.setXnd(scholarshipApply.getXnd());
          studentScoreConductList = commonService.querySemesterStudentScoreConductList(student);
        }
        // 获取审评结果
        model.put("cxGrade1", cxGrade1);
        model.put("cxGrade2", cxGrade2);
        model.put("familyList", familyList);
        model.put("studentScoreConductList", studentScoreConductList);
        model.put("scholarshipApply", scholarshipApply);
        model.put("msg", BaseController.getParameter("msg"));
        BaseController.removeParameter("msg");
        model.put("bzr", request.getParameter("bzr"));
        return "scholarship/viewScholarshipStudent";
      } else {
        BaseController.setParameter("msg", "没权限访问该页面");
        return "redirect:scholarshipStudentManagerIndex";
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("学生申请奖学金(管理端)详情查看 viewStudentScholarshipManagerForward [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }

  }

  /**
   * 导出学生奖学金列表数据
   * 
   * @param request
   * @param response
   * @param bodyData
   * @throws Exception
   */
  @RequestMapping(value = "/exportManagerStudentScholarshipApply")
  public @ResponseBody String exportManagerStudentScholarshipApply(HttpServletRequest request,
      HttpServletResponse response, /* @RequestParam("bodyData") String bodyData, */ ModelMap model,
      ScholarshipApply data) throws Exception {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    try {
      String[][] title_name = {{"姓名", "学号", "班级", "专业", "年级", "学年", "奖学金等级"}};
      String[] title_style = {"hwzs_16_bold_25", "kt_12_bold_18", "st_12_r_20", "st_12_n_20"};
      String fileName = "学生奖学金信息";
      String[] remark = {""};
      List<Map<String, Object>> exportlist = new ArrayList<Map<String, Object>>();
      if (loginType == 2) { // 老师
        UserEmployee userEmployee =
            (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
        Page page = BaseController.getPage("0", "0", request, "xnd", "desc");
        String ismanager = request.getParameter("ismanager");
        data.setOrderField((String) request.getAttribute("orderField"));
        data.setOrderFlag((String) request.getAttribute("orderFlag"));
        data.setStates(FlowApprovalState.state3.getIndex());
        if (Constant.IS_BZR.equals(ismanager)) {
          data.setBzrid(userEmployee.getEmid());
        }
        // List<ScholarshipApply> list = JSONArray.parseArray(bodyData, ScholarshipApply.class);
        List<ScholarshipApply> list =
            scholarshipApplyService.exportScholarshipApplyManagerList(data);
        if (!list.isEmpty()) {
          for (ScholarshipApply res : list) {
            Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("name", res.getXm());
            map.put("xh", res.getXh());
            map.put("bjmc", res.getBjmc());
            map.put("bjmc", res.getBjmc());
            map.put("zymc", res.getZymc());
            map.put("njmc", res.getNjmc());
            map.put("xn", res.getXnd());
            map.put("jxjdj", res.getJxjdj());
            exportlist.add(map);
          }
        }
      }
      HSSFWorkbook wb =
          ExpExcelUtil.getWorkBookExcel(title_name, title_style, 100, remark, fileName, exportlist);
      response.reset();
      response.setContentType("application/vnd.ms-excel;charset=utf-8");
      response.setHeader("Content-Disposition",
          "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
      response.setDateHeader("Expires", 0);
      ServletOutputStream os = response.getOutputStream();
      wb.write(os);
      os.flush();
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("导出学生奖学金信息 exportManagerStudentScholarshipApply [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return null;
  }

  /**
   * 导出班级学生奖学金汇总表数据
   * 
   * @param request
   * @param response
   * @param bodyData
   * @throws Exception
   */
  @RequestMapping(value = "/exportManagerClassStudentScholarshipApply")
  public @ResponseBody String exportManagerClassStudentScholarshipApply(HttpServletRequest request,
      HttpServletResponse response, ModelMap model) throws Exception {
    Integer loginType = (Integer) request.getSession().getAttribute(Constant.LOGIN_USER_TYPE);
    HSSFWorkbook wb = null;
    try {
      String rows = request.getParameter("paramRowsLength");
      String cols = request.getParameter("paramColsLength");
      String paramHead = request.getParameter("paramHead");
      String paramAllContent = request.getParameter("paramAllContent");
      String fileName = request.getParameter("fileName");
      String titleName = fileName;
      if (StringUtils.isNullValue(fileName)) {
        fileName = "sheet.xls";
        titleName = "";
      }
      if (!fileName.toLowerCase().endsWith(".xls")) {
        fileName = fileName + ".xls";
      }
      // String exportFlag = request.getParameter("exportFlag");
      wb = POIUtil.getStatXls(rows, cols, paramHead, paramAllContent, titleName);
      response.reset();
      response.setContentType("application/msexcel");
      response.setHeader("Content-disposition",
          "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO-8859-1"));// 定义文件名
      OutputStream out = response.getOutputStream();
      wb.write(out);
      out.flush();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("导出导出班级学生奖学金汇总表数据 exportManagerClassStudentScholarshipApply [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return null;
  }

  /**
   * 班级汇总学生奖学金名单信息
   * 
   * @param request
   * @param response
   * @param xsid
   * @param xnd
   * @return
   */
  @RequestMapping(value = "/getStudentScholarshipReport")
  public String getStudentScholarshipReport(ModelMap model, HttpServletRequest request,
      HttpServletResponse response, @RequestParam(value = "bjid") Integer bjid,
      @RequestParam(value = "xnd") Integer xnd) {
    response.setContentType("text/html;charset=utf-8");
    try {
      if (bjid == null || xnd == null) {
        return null;
      } else {
        String bzr = request.getParameter("bzr");
        ScholarshipApply scholarshipApply = new ScholarshipApply();
        scholarshipApply.setXnd(xnd);
        scholarshipApply.setBjid(bjid);
        if (!StringUtils.isNullValue(bzr) && Constant.IS_BZR.equals(bzr)) {
          UserEmployee userEmployee =
              (UserEmployee) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
          scholarshipApply.setBzrid(userEmployee.getEmid());
        }
        // 判断评定等级情况
        List<ScholarshipApply> scholarshipApplyList =
            scholarshipApplyService.queryClassByScholarshipapplyReport(scholarshipApply);
        // 一等奖学金
        List<ScholarshipApply> studentScholarshipApplyList1 =
            getStudentScholarshipReportList(scholarshipApplyList, 1);
        // 二等奖学金
        List<ScholarshipApply> studentScholarshipApplyList2 =
            getStudentScholarshipReportList(scholarshipApplyList, 2);
        // 三等奖学金
        List<ScholarshipApply> studentScholarshipApplyList3 =
            getStudentScholarshipReportList(scholarshipApplyList, 3);
        model.put("studentScholarshipApplyList1", studentScholarshipApplyList1);
        model.put("studentScholarshipApplyList2", studentScholarshipApplyList2);
        model.put("studentScholarshipApplyList3", studentScholarshipApplyList3);
        model.put("size1", studentScholarshipApplyList1.size());
        model.put("size2", studentScholarshipApplyList2.size());
        model.put("size3", studentScholarshipApplyList3.size());
        // 获得年级、班级信息
        StudentClass studentClass = commonService.queryStudentClass(bjid);
        Grade g = new Grade();
        g.setNjid(studentClass.getNjid());
        Grade grade = commonService.queryByGrade(g);
        model.put("grade", grade);
        model.put("studentClass", studentClass);
        model.put(BaseController.TEACHER_IS_MANAGER, bzr);
      }
    } catch (Exception e) {
      e.printStackTrace();
      LOGGER.error("班级汇总学生奖学金名单信息 getStudentScholarshipReport [{}] error,"
          + this.getClass().getName() + "=[{}]", this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
    return "scholarship/scholarshipStudent_managerReport";
  }

  private static List<ScholarshipApply> getStudentScholarshipReportList(
      List<ScholarshipApply> scholarshipApplyList, Integer jxjdj) {
    List<ScholarshipApply> studentScholarshipApplyList = new ArrayList<ScholarshipApply>();
    for (ScholarshipApply y : scholarshipApplyList) {
      if (jxjdj.intValue() == y.getJxjdj().intValue()) {
        studentScholarshipApplyList.add(y);
      }
    }
    return studentScholarshipApplyList;
  }

  /**
   * 获得学金获得者登记表信息
   * 
   * @param model
   * @param request
   * @param sqid
   * @return
   */
  @RequestMapping(value = "/studentScholarshipRegister")
  public String studentScholarshipRegister(ModelMap model, HttpServletRequest request,
      @RequestParam(value = "sqid") Integer sqid) {
    try {
      ScholarshipApply scholarshipApply = scholarshipApplyService.queryByScholarshipApplyPk(sqid);
      List<StudentFamily> familyList = new ArrayList<StudentFamily>();
      // List<Student> studentScoreConductList = new ArrayList<Student>();
      Student student = (Student) request.getSession().getAttribute(Constant.LOGIN_CONSOLE_USER);
      if (scholarshipApply != null && scholarshipApply.getSqid() != null) {
        // 获得学生的家庭成员信息
        StudentFamily family = new StudentFamily();
        family.setStuid(student.getXsid());
        familyList = commonService.queryStudentByAllFamily(family);
        // 获得评定成绩信息
        // student.setYxid(null);
        // student.setXnd(scholarshipApply.getXnd());
        // List<Student> studentScoreConductList =
        // commonService.querySemesterStudentScoreConductList(student);
        // 获得助学金
        ZxjStudentNationalGrant zxjStudentNationalGrant = new ZxjStudentNationalGrant();
        zxjStudentNationalGrant.setStuid(scholarshipApply.getStuid());
        int num =
            zxjStudentNationalGrantService.queryStudentNationalGrantCount(zxjStudentNationalGrant);

        // 获得人民助学金
        ZxjStudentPeopleGrant zxjStudentPeopleGrant = new ZxjStudentPeopleGrant();
        zxjStudentPeopleGrant.setStuid(scholarshipApply.getStuid());
        int num2 = zxjStudentPeopleGrantervice.queryStudentPeopleGrantCount(zxjStudentPeopleGrant);
        if (num >= 1 && num2 <= 0) {
          scholarshipApply.setZxzzqk("获得过助学金");
        } else if (num >= 0 && num2 >= 1) {
          scholarshipApply.setZxzzqk("获得过人民助学金");
        } else if (num >= 1 && num2 >= 1) {
          scholarshipApply.setZxzzqk("获得过助学金、人民助学金");
        } else {
          scholarshipApply.setZxzzqk(null);
        }
      }
      scholarshipApply.setRxrq(student.getRxrq());
      scholarshipApply.setZymc(student.getZymc());
      scholarshipApply.setXb(student.getXb());
      scholarshipApply.setNjmc(student.getNjmc());
      scholarshipApply.setXm(student.getXm());
      scholarshipApply.setSfzh(student.getSfzh());
      if (student.getCsrq() == null) {
        scholarshipApply.setCsrq(
            DateUtil.parseStr2Date(IdCardUtils.getIdCardBirthday(student.getSfzh()), "yyyy-MM-dd"));
      } else {
        scholarshipApply.setCsrq(student.getCsrq());
      }
      model.put("scholarshipApply", scholarshipApply);
      model.put("familyList", familyList);
      return "scholarship/registerScholarshipStudent";
    } catch (Exception e) {
      LOGGER.error(
          "学生奖学金登记信息 studentScholarshipRegister [{}] error," + this.getClass().getName() + "=[{}]",
          this.getClass().getName(), e.getMessage());
      model.addAttribute(Constant.EXPTION_MSG_KEY, e);
      return "error/error";
    }
  }
}
